package com.xukang.demo.controller;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * ribbon 负载均衡原理
 */
@RestController
public class DiscoveryController {

    @Autowired
    private DiscoveryClient client;

    private int reqCount = 0;

    /**
     * 负载获取调用的rpc 地址
     * @return
     */
    @RequestMapping("/getServicesUri")
    public String discoveryClent() {
        List<String> serviceList = client.getServices();
        System.out.println("注册服务的数量>>>>>>>>>>>>>>>>>" + serviceList.size());
        for (String service : serviceList) {
            System.out.println("注册的服务名>>>>>>" + service);
        }
        List<ServiceInstance> list2 =client.getInstances("springeureka-demo2");
        if(list2 ==null  || list2.size()<=0){
            return null;
        }
        int instancesize = list2.size();
        int instanceIndex = reqCount % instancesize;
        reqCount++;
        return list2.get(instanceIndex).getUri().toString();
    }
}
